package com.octant.testtcpudp;

import android.util.Log;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Arrays;

public class TcpServerRunnable implements Runnable {
    private String TAG = "TcpServerRunnable";

    private ServerSocket server;	//设置服务器套接字
    private Socket client;		//设置客户端套接字
    private int port = 8080;
    private byte[] senddata_a;
    private boolean sendFlag = false;

    private String clientIp;
    private int clientPort;

    public TcpServerRunnable(int port) {
        this.port = port;
    }

    public void sendData(byte[] data){
        senddata_a = data;
        sendFlag = true;
    }

    public int getPort() {
        return port;
    }

    public String getClientIp() {
        return clientIp;
    }

    public int getClientPort() {
        return clientPort;
    }

    @Override
    public void run() {
        try{
            //限制一个客户端可以同时连接
            server = new ServerSocket(port,1);
        }catch(Exception e){
            e.printStackTrace();
            if (listener != null){
                listener.onTcpServerClose();
            }
            Log.i(TAG,"onTcpServerClose");
            return;
        }
        while (true){
            try{
                client = server.accept();
                InetSocketAddress socketAddress = (InetSocketAddress) client.getRemoteSocketAddress();
                clientIp = socketAddress.getHostName();
                clientPort = socketAddress.getPort();
                if (listener != null){
                    listener.onTcpServerAcceptClient(true,clientIp,clientPort);
                }
                Log.i(TAG,"onTcpServerAcceptClient,true,"+clientIp+","+clientPort);
            }catch(Exception e){
                e.printStackTrace();
                break;
            }

            InputStream in = null;
            OutputStream out = null;
            try {
                in = client.getInputStream();	//获取到客户端的输入流
                out = client.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }

            while (client != null && client.isClosed()==false && client.isConnected()) {
                try {
                    if (in.available()>0) {
                        byte[] b = new byte[1024];    //定义字节数组
                        int len = in.read(b);
                        if (listener != null){
                            listener.onTcpServerReceiveData(b,len,port,client.getInetAddress().toString(),client.getPort());
                        }
                        Log.i(TAG,"onTcpServerReceiveData,"+HexUtil.bytesToHex(Arrays.copyOf(b,len)));
                    }

                    if (sendFlag) {
                        out.write(senddata_a);
                        sendFlag = false;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    break;
                }

                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (server == null || server.isClosed()){
                    break;
                }
            }
            if (listener != null){
                listener.onTcpServerAcceptClient(false,clientIp,clientPort);
            }
            Log.i(TAG,"onTcpServerAcceptClient,false");
        }
        close();
        if (listener != null){
            listener.onTcpServerClose();
        }
        Log.i(TAG,"onTcpServerClose");
    }

    public void close(){
        if (server != null){
            try {
                server.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        server = null;
    }

    private TcpServerListener listener;

    public void setListener(TcpServerListener listener) {
        this.listener = listener;
    }

    public interface TcpServerListener{
        void onTcpServerAcceptClient(boolean flag,String clientIp,int clientPort);
        void onTcpServerReceiveData(byte[] data,int len,int port,String clientIp,int clientPort);
        void onTcpServerClose();
    }

}
